import { WeilaNetworkInterface} from '../store/weila_datas';


export class WeilaH5Network implements WeilaNetworkInterface {
    private socket: WebSocket|null;
    private onConnectCb?: () => void;
    private onDisconnectCb?: () => void;
    private onRecvCb?: (data: Uint8Array) => void;
    private onErrorCb?: (error: any) => void;

    constructor() {
        this.socket = null;
    }

    public close(): void {
        this.socket?.close();
    }

    public send(data: Uint8Array): void {
        this.socket?.send(data);
    }

    public connect(url: string): void {
        try {
            this.socket = new WebSocket(url);

            this.socket.binaryType = "arraybuffer";
            this.socket.onopen = this.onSocketOpen.bind(this);
            this.socket.onmessage = this.onSocketRecv.bind(this);
            this.socket.onclose = this.onSocketClose.bind(this);
            this.socket.onerror = this.onSocketError.bind(this);
        }catch (e) {
            console.log('连接WS Socket 出异常', e);
        }
    }


    public disconnect(): void {
        this.socket?.close(0, 'normal close');
    }


    public onConnect(onConnect: () => void): void {
        this.onConnectCb = onConnect;
    }

    public onClose(onClose: () => void): void {
        this.onDisconnectCb = onClose;
    }

    public onError(onError: (error: any) => void): void {
        this.onErrorCb = onError;
    }

    public onRecv(onRecv: (data: Uint8Array) => void): void {
        this.onRecvCb = onRecv;
    }

    private onSocketOpen(event: Event) {
        console.log('服务器连接成功');
        if (this.socket) {
            if (this.socket.readyState == WebSocket.OPEN) {
                if (this.onConnectCb) {
                    this.onConnectCb();
                }
            }
        }
    }

    private onSocketRecv(event: Event) {
        console.log('收到消息', event);
        if (this.onRecvCb) {
            this.onRecvCb(new Uint8Array((event as MessageEvent).data));
        }
    }

    private onSocketClose(event: Event) {
        console.log('服务器连接断开', event);
        if (this.onDisconnectCb) {
            this.onDisconnectCb();
        }
    }   

    private onSocketError(event: Event) {
        console.log('服务器连接出错');
        if (this.onErrorCb) {
            this.onErrorCb(JSON.stringify(event));
        }
    }
}